//
//  HobbiesViewController.m
//  iShop
//
//  Created by svp on 18/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HobbiesViewController.h"
#import "ResourceLoader.h"
#import "SelectBrandViewController.h"
//#import "PickerValueCell.h"
#import "SelectPriceRangeViewController.h"
#import "TitleTextfieldCell.h"
#import "ProductDetailViewController.h"
#import "HobbiesSubCategoryViewController.h"
#import "CoreDataUtils.h"
#import "Category.h"
#import "Brand.h"
#import "Utils.h"

@interface HobbiesViewController(Private)

-(void) keyboardDidShow:(NSNotification*)notification;
-(void) keyboardDidHide:(NSNotification*)notification;

@end

//enum EHobbiesRow {
//	EBrandRow,
//	ESizeRow,
//	EPriceRow,
//	EHobbiesRowCount,
//};

@implementation HobbiesViewController

@synthesize tableView = _tableView;
@synthesize changeModeButton = _changeModeButton;
@synthesize toolbar = _toolbar;
@synthesize navItem = _navItem;
@synthesize customSegment = _customSegment;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
	 _keyboardHeight = 0;
 }
 return self;
 }
 

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	self.navigationItem.leftBarButtonItem = _navItem.leftBarButtonItem;
	self.navigationItem.rightBarButtonItem = _navItem.rightBarButtonItem;
	self.navigationItem.titleView = _navItem.titleView;
	//_sortCategories = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:@"Man",@"Woman",@"Baby",@"Child",nil]];
	_sortCategories = [[NSMutableArray alloc] initWithArray:[CoreDataUtils getMainCategory]];
	_wishlistProducts = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:@"product 1",@"product 2",@"product 3",@"product 4",@"product 5",@"product 6",nil]];

	//_brands = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:@"Foci",@"Ninomax",@"VietTien",@"VietThi",nil]];
	_brands = [[NSMutableArray alloc] initWithArray:[CoreDataUtils getBrandList]];


	//_selectBrand = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:[NSNumber numberWithBool:NO],[NSNumber numberWithBool:NO],[NSNumber numberWithBool:NO],[NSNumber numberWithBool:NO],nil]];
	//_selectBrand = [[NSMutableArray alloc] init];
//	for (int i=0; i<_brands.count; i++) {
//		
//		[_selectBrand addObject:[NSNumber numberWithBool:NO]];
//	}
	_customSegment.selectedSegmentIndex = 0;
	
	//_tableView.editing = YES;
	
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditCell)];
	
	// For selecting cell.
	gestureRecognizer.cancelsTouchesInView = NO;
	
	[_tableView addGestureRecognizer:gestureRecognizer];
	
	[gestureRecognizer release];
}

-(void) endEditCell
{
	if (_keyboardHeight != 0) {
		[_tableView endEditing:YES];
		[self keyboardDidHide:nil];
	}
}

-(void) keyboardDidShow:(NSNotification*)notification
{
	NSLog(@"keyboardDidShow");
	if (_keyboardHeight != 0) {
		return;
	}
	NSDictionary* info = [notification userInfo];
	NSLog(@"notification:%@",info);
	NSLog(@"test%@",[_tableView indexPathForSelectedRow]);
	NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	_keyboardHeight = [aValue CGRectValue].size.height;
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height - _keyboardHeight);
	[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:_editCell] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
	
}

-(void) keyboardDidHide:(NSNotification *)notification
{
	NSLog(@"keyboardDidHide");
	if (_keyboardHeight == 0) {
		return;
	}
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height + _keyboardHeight);
	_keyboardHeight = 0;
}

-(void) viewWillAppear:(BOOL)animated
{
	NSLog(@"viewWillAppear");
	[super viewWillAppear:animated];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector (keyboardDidShow:)
												 name: UIKeyboardWillShowNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector (keyboardDidHide:)
												 name: UIKeyboardDidHideNotification object:nil];
}

-(void) viewWillDisappear:(BOOL)animated
{
	NSLog(@"viewWillDisappear");
	[super viewWillDisappear:animated];	
	[(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] saveContext];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc {
	NSLog(@"HobbiesViewController dealloc");
	//category order
	UpdateCategoryOrderRequest *req = [[UpdateCategoryOrderRequest alloc] init];
	NSMutableArray *categoryOrders = [[[NSMutableArray alloc] init] autorelease];
	for (Category *cat in _sortCategories) {
		NSMutableDictionary *catInfo = [[NSMutableDictionary alloc] init];
		[catInfo setObject:cat.CategoryID forKey:@"CategoryID"];
		[catInfo setObject:cat.CustomerCategoryOrder forKey:@"CategoryOrder"];
		[categoryOrders addObject:catInfo];
		[catInfo release];
	}
	NSMutableDictionary *infomation = [[[NSMutableDictionary alloc] init] autorelease];
	[infomation setObject:[Utils getValueForRefKey:kSessionKey] forKey:KSessionKey];
	[infomation setObject:categoryOrders forKey:@"CustomerCategoryOrders"];
	[req makeRequest:infomation];
	//customer brand
	UpdateBrandCheckRequest *req1 = [[UpdateBrandCheckRequest alloc] init];
	NSMutableArray *brandChecks = [[[NSMutableArray alloc] init] autorelease];
	for (Brand *brand in _brands) {
		NSMutableDictionary *brandInfo = [[NSMutableDictionary alloc] init];
		[brandInfo setObject:brand.BrandID forKey:@"BrandID"];
		[brandInfo setObject:brand.BrandCheck forKey:@"BrandSelected"];
		[brandChecks addObject:brandInfo];
		[brandInfo release];
	}
	NSMutableDictionary *infomation1 = [[[NSMutableDictionary alloc] init] autorelease];
	[infomation1 setObject:[Utils getValueForRefKey:kSessionKey] forKey:KSessionKey];
	[infomation1 setObject:brandChecks forKey:@"CustomerBrandChecks"];
	[req1 makeRequest:infomation1];
	[_tableView release];
    [super dealloc];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEditing]){
		return YES;
    }
	
    return NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if (_customSegment.selectedSegmentIndex == 0) {
		return 2;
	}
	else { 
		return _wishlistProducts.count;
	}

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if (_customSegment.selectedSegmentIndex == 0) {
		if (section == 0) {
			return @"Sort Priority";
		}
		else {
			return @"Brand like most";
		}

	}
	else {
		return @"";
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
	if (_customSegment.selectedSegmentIndex == 0) {
		if (indexPath.section == 0) {
			return 70;
		}
		return 44;	
	}
	else {
		return 44;
	}

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//return count + [tableView isEditing];
	if (_customSegment.selectedSegmentIndex == 0) {
		if (section == 0) {
			return _sortCategories.count;
		}
		else {
			return _brands.count;
		}

		//return EHobbiesRowCount;
	}
	else {
		return 1;
	}
}

-(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle

forRowAtIndexPath:(NSIndexPath *)indexPath

{
	
    if (editingStyle == UITableViewCellEditingStyleDelete)		
    {		
		[_wishlistProducts removeObjectAtIndex:indexPath.section];
		[tableView reloadData];
    } 
	
	
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (_customSegment.selectedSegmentIndex == 0) {
		if (indexPath.section == 0) {
			HobbiesSortCell* cell = (HobbiesSortCell*)[tableView dequeueReusableCellWithIdentifier:@"HobbiesSortCell"];
			if (!cell) {
				ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"HobbiesSortCell"] autorelease];
				cell = (HobbiesSortCell*)rc.resource;
				cell.delegate = self;
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			}
			//cell.category.text = [_sortCategories objectAtIndex:indexPath.row];
			cell.category.text = ((Category*)[_sortCategories objectAtIndex:indexPath.row]).CategoryName;
			return cell;
		}
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
		if (!cell) {
			NSLog(@"Create cell");
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
		}
		//cell.accessoryType = [[_selectBrand objectAtIndex:indexPath.row] boolValue]?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
		cell.accessoryType = [((Brand*)[_brands objectAtIndex:indexPath.row]).BrandCheck boolValue]?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
		//cell.textLabel.text = [_brands objectAtIndex:indexPath.row];
		cell.textLabel.text = ((Brand*)[_brands objectAtIndex:indexPath.row]).BrandName;
		return cell;
		//if (indexPath.row == ESizeRow) {
//			TitleTextfieldCell* cell = (TitleTextfieldCell*)[tableView dequeueReusableCellWithIdentifier:@"TitleTextfieldCell"];
//			if (!cell) {
//				ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"TitleTextfieldCell"] autorelease];
//				cell = (TitleTextfieldCell*)rc.resource;
//				cell.delegate = self;
//				[cell initPickerWithArray:[NSArray arrayWithObjects:@"A",@"B",@"C",nil]];
//			}
//			cell.titleLabel.text = @"Size";
//			return cell;
//		}
//		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
//		if (!cell) {
//			NSLog(@"Create cell");
//			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
//			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//		}
//		cell.textLabel.text = indexPath.row == EBrandRow? @"Brand": @"Price";
//		return cell;
	}
	else {
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
		if (!cell) {
			NSLog(@"Create cell");
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
		cell.textLabel.text = [_wishlistProducts objectAtIndex:indexPath.section];
		cell.accessoryType = UITableViewCellAccessoryNone;
		return cell;
	}

		
	
	
	
	
	

	
	//if (![tableView isEditing] || ([tableView isEditing] && indexPath.row != count)) {
//		cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ico_ip_chat" ofType:@"png"]];
//		cell.imageView.backgroundColor = [UIColor redColor];
//		cell.textLabel.text = @"Field";
//		cell.detailTextLabel.text = @"Value";
//		UIImageView *temp = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ico_ip_chat" ofType:@"png"]]];
//		temp.backgroundColor = [UIColor yellowColor];
//		cell.accessoryView = temp;
//		[temp release];
//	}
//	else if([tableView isEditing]){
//		cell.textLabel.text = @"More San pham";
//	}
	
	return nil;
}

-(void) textFieldDidBeginEditing:(UITableViewCell*)cell
{
	NSLog(@"BBB");
	_editCell = cell;
	[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:_editCell] atScrollPosition:UITableViewScrollPositionBottom animated:NO];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"didSelectRowAtIndexPath:%@",indexPath);
	if (_customSegment.selectedSegmentIndex == 0) {
		if (indexPath.section > 0) {
			//NSNumber *newValue = [NSNumber numberWithBool:![[_selectBrand objectAtIndex:indexPath.row] boolValue]];
			//[_selectBrand replaceObjectAtIndex:indexPath.row withObject:newValue];
			//[[_selectBrand objectAtIndex:indexPath.row] boolValue] = ![[_selectBrand objectAtIndex:indexPath.row] boolValue];
			((Brand*)[_brands objectAtIndex:indexPath.row]).BrandCheck = [NSNumber numberWithBool:![((Brand*)[_brands objectAtIndex:indexPath.row]).BrandCheck boolValue]];
			[_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
			return;
		}
		else {
			HobbiesSubCategoryViewController *custom = [[HobbiesSubCategoryViewController alloc] initWithNibName:@"HobbiesSubCategoryViewController" bundle: nil];
			custom.parentCategory = [_sortCategories objectAtIndex:indexPath.row];
			[self.navigationController pushViewController:custom animated:YES];
			[custom release];
		}

		//if (indexPath.section > 0 && indexPath.row == EBrandRow) {		
//			SelectBrandViewController *custom = [[SelectBrandViewController alloc] initWithNibName:@"SelectBrandViewController" bundle: nil];
//			[self.navigationController pushViewController:custom animated:YES];
//			[custom release];
//		}
//		
//		if (indexPath.section > 0 && indexPath.row == EPriceRow) {		
//			SelectPriceRangeViewController *custom = [[SelectPriceRangeViewController alloc] initWithNibName:@"SelectPriceRangeViewController" bundle: nil];
//			[self.navigationController pushViewController:custom animated:YES];
//			[custom release];
//		}
	}
	else {
		ProductDetailViewController *custom = [[ProductDetailViewController alloc] initWithNibName:@"ProductDetailViewController" bundle: nil];
		//custom.productindex = indexPath.section+1;
		[custom setHideToolbar:YES];
		[self.navigationController pushViewController:custom animated:YES];
		[custom release];
	}

}

-(IBAction) savePress:(id) sender;
{
	NSLog(@"savePress");
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction) cancelPress:(id) sender;
{
	NSLog(@"cancelPress");
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction) changeMode:(id) sender
{
	BOOL canEdit = [_tableView isEditing];
	canEdit = !canEdit;
	_tableView.editing = canEdit;
	_changeModeButton.style =  canEdit ? UIBarButtonItemStyleDone : UIBarButtonItemStyleBordered;
	[_tableView reloadData];
}

-(void) moveUp:(HobbiesSortCell*)cell
{
	NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
	NSLog(@"move up %i",indexPath.row);
	if (indexPath.row > 0) {
		int curr = [((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder intValue];
		int new = [((Category*)[_sortCategories objectAtIndex:indexPath.row - 1]).CustomerCategoryOrder intValue];
		[_sortCategories exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row - 1];
		((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder = [NSNumber numberWithInt:curr];
		((Category*)[_sortCategories objectAtIndex:indexPath.row - 1]).CustomerCategoryOrder = [NSNumber numberWithInt:new];
		[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];
		[_tableView reloadData];
	}
}

-(void) moveDown:(HobbiesSortCell*)cell
{
	NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
	NSLog(@"move Down %i",indexPath.row);
	if (indexPath.row < [_tableView numberOfRowsInSection:indexPath.section] - 1 ) {
		int curr = [((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder intValue];
		int new = [((Category*)[_sortCategories objectAtIndex:indexPath.row + 1]).CustomerCategoryOrder intValue];
		[_sortCategories exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row + 1];
		((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder = [NSNumber numberWithInt:curr];
		((Category*)[_sortCategories objectAtIndex:indexPath.row + 1]).CustomerCategoryOrder = [NSNumber numberWithInt:new];
		[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];
		[_tableView reloadData];
	}
}

-(IBAction) segmentChange:(id) sender
{
	if (_customSegment.selectedSegmentIndex == 0) {
		[_tableView endEditing:YES];
		[_toolbar removeFromSuperview];
		_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height + _toolbar.frame.size.height);
	}
	else {
		[self.view addSubview:_toolbar];
		_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height - _toolbar.frame.size.height);
	}

	[_tableView reloadData];
}
@end
